<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>精美数据表格</title>
    <style>
        /* 全局样式重置与基础设置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #333;
            padding: 20px;
        }

        /* 表格容器样式 */
        .table-container {
            background: white;
            padding: 2rem;
            border-radius: 16px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 1200px;
            overflow: hidden;
            transform: translateY(0);
            opacity: 1;
            transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        /* 表格标题 */
        .table-title {
            text-align: center;
            margin-bottom: 1.5rem;
            color: #444;
            font-size: 1.8rem;
            font-weight: 600;
            position: relative;
        }

        .table-title::after {
            content: '';
            display: block;
            width: 60px;
            height: 4px;
            background: #667eea;
            margin: 10px auto;
            border-radius: 2px;
            transition: width 0.3s ease;
        }

        .table-title:hover::after {
            width: 100px;
        }

        /* 工具栏样式 - 搜索、添加等操作 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .search-box {
            display: flex;
            align-items: center;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px 12px;
            flex: 1;
            min-width: 200px;
            transition: all 0.3s ease;
        }

        .search-box:focus-within {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .search-box input {
            border: none;
            outline: none;
            background: transparent;
            padding: 4px;
            font-size: 1rem;
            color: #333;
            width: 100%;
        }

        .search-icon {
            color: #999;
            margin-right: 8px;
            font-size: 1.1rem;
        }

        /* 添加按钮样式 */
        .add-btn {
            background: linear-gradient(to right, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 2px 5px rgba(102, 126, 234, 0.2);
        }

        .add-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(102, 126, 234, 0.3);
        }

        .add-btn:active {
            transform: translateY(0);
        }

        /* 数据表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 0.95rem;
            min-width: 500px;
        }

        /* 表头样式 */
        .data-table thead th {
            background: linear-gradient(to bottom, #667eea, #5a6fd8);
            color: white;
            text-align: left;
            padding: 15px 12px;
            font-weight: 600;
            position: relative;
            cursor: pointer;
            user-select: none;
            transition: background 0.3s ease;
        }

        .data-table thead th:hover {
            background: linear-gradient(to bottom, #5a6fd8, #4e62c5);
        }

        /* 排序图标 */
        .sort-icon {
            margin-left: 8px;
            font-size: 0.8rem;
            opacity: 0.7;
            transition: all 0.2s ease;
        }

        .sort-icon.active {
            opacity: 1;
            transform: scale(1.2);
        }

        /* 表格行样式 */
        .data-table tbody tr {
            border-bottom: 1px solid #eeeeee;
            transition: all 0.3s ease;
        }

        .data-table tbody tr:hover {
            background-color: #f8f9ff;
            transform: translateY(-2px);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
        }

        /* 表格单元格样式 */
        .data-table tbody td {
            padding: 14px 12px;
            color: #555;
        }

        /* 操作列样式 */
        .action-cell {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
        }

        /* 编辑按钮 */
        .edit-btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .edit-btn:hover {
            background: #45a049;
            transform: scale(1.05);
        }

        /* 删除按钮 */
        .delete-btn {
            background: #f44336;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .delete-btn:hover {
            background: #da190b;
            transform: scale(1.05);
        }

        /* 状态标签样式 */
        .status-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            display: inline-block;
        }

        .status-active {
            background: #e8f5e9;
            color: #2e7d32;
        }

        .status-inactive {
            background: #ffebee;
            color: #c62828;
        }

        .status-pending {
            background: #fff8e1;
            color: #f57f17;
        }

        /* 分页控件样式 */
        .pagination {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1.5rem;
            padding: 1rem 0;
            border-top: 1px solid #eee;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .page-info {
            color: #666;
            font-size: 0.9rem;
        }

        .page-controls {
            display: flex;
            gap: 8px;
        }

        .page-btn {
            background: white;
            border: 1px solid #ddd;
            color: #555;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 40px;
            text-align: center;
        }

        .page-btn:hover {
            background: #f8f9fa;
            border-color: #667eea;
            color: #667eea;
        }

        .page-btn.active {
            background: #667eea;
            border-color: #667eea;
            color: white;
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 模态框样式（用于添加/编辑） */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modal.show {
            display: flex;
            opacity: 1;
        }

        .modal-content {
            background: white;
            padding: 2rem;
            border-radius: 16px;
            width: 100%;
            max-width: 500px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
            transform: translateY(-50px);
            transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        }

        .modal.show .modal-content {
            transform: translateY(0);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #eee;
        }

        .modal-title {
            font-size: 1.5rem;
            color: #444;
            font-weight: 600;
        }

        .close-btn {
            background: #f8f9fa;
            border: none;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 1.2rem;
            color: #999;
            transition: all 0.2s ease;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .close-btn:hover {
            background: #e9ecef;
            color: #666;
            transform: rotate(90deg);
        }

        /* 模态框表单样式 */
        .modal-form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-label {
            margin-bottom: 0.5rem;
            color: #555;
            font-weight: 500;
            font-size: 0.95rem;
        }

        .form-input,
        .form-select {
            padding: 10px 14px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            outline: none;
        }

        .form-input:focus,
        .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 模态框按钮 */
        .modal-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-cancel {
            background: #f8f9fa;
            color: #495057;
        }

        .btn-cancel:hover {
            background: #e9ecef;
        }

        .btn-save {
            background: linear-gradient(to right, #667eea, #764ba2);
            color: white;
            box-shadow: 0 2px 5px rgba(102, 126, 234, 0.2);
        }

        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 15px rgba(102, 126, 234, 0.3);
        }

        /* 加载状态样式 */
        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空数据状态 */
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #999;
            font-style: italic;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .table-container {
                padding: 1rem;
                margin: 10px;
            }

            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }

            .search-box {
                min-width: auto;
            }

            .data-table {
                font-size: 0.85rem;
            }

            .data-table thead {
                display: none;
            }

            .data-table tbody tr {
                display: block;
                margin-bottom: 15px;
                border: 1px solid #eee;
                border-radius: 8px;
                padding: 10px;
            }

            .data-table tbody td {
                display: block;
                padding: 8px 0;
                text-align: right;
                position: relative;
                padding-right: 120px;
            }

            .data-table tbody td::before {
                content: attr(data-label);
                position: absolute;
                left: 12px;
                width: 100px;
                font-weight: 600;
                color: #555;
                text-align: left;
            }

            .action-cell {
                justify-content: center;
                padding: 10px 0 0 0;
            }

            .pagination {
                flex-direction: column;
                align-items: center;
            }

            .page-info {
                text-align: center;
            }
        }
    </style>
</head>
<body>
<!-- 表格容器 -->
<div class="table-container" id="tableContainer">
    <!-- 表格标题 -->
    <h2 class="table-title">用户管理表格</h2>

    <!-- 工具栏 -->
    <div class="toolbar">
        <!-- 搜索框 -->
        <div class="search-box">
            <span class="search-icon">🔍</span>
            <input
                    type="text"
                    id="searchInput"
                    placeholder="搜索用户..."
            />
        </div>

        <!-- 添加按钮 -->
        <button class="add-btn" id="addBtn">
            <span>+</span>
            <span>添加用户</span>
        </button>
    </div>

    <!-- 数据表格 -->
    <table class="data-table" id="dataTable">
        <thead>
        <tr>
            <th data-sort="id">
                ID
                <span class="sort-icon">↑↓</span>
            </th>
            <th data-sort="name">
                姓名
                <span class="sort-icon">↑↓</span>
            </th>
            <th data-sort="email">
                邮箱
                <span class="sort-icon">↑↓</span>
            </th>
            <th data-sort="department">
                部门
                <span class="sort-icon">↑↓</span>
            </th>
            <th data-sort="status">
                状态
                <span class="sort-icon">↑↓</span>
            </th>
            <th data-sort="joinDate">
                入职日期
                <span class="sort-icon">↑↓</span>
            </th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="tableBody">
        <!-- 表格数据将通过JavaScript动态生成 -->
        <tr>
            <td colspan="7" class="loading">
                <span class="loading-spinner"></span>
                <span>加载中...</span>
            </td>
        </tr>
        </tbody>
    </table>

    <!-- 分页控件 -->
    <div class="pagination">
        <div class="page-info" id="pageInfo">共 0 条记录，每页 10 条</div>
        <div class="page-controls">
            <button class="page-btn" id="prevPage" disabled>上一页</button>
            <button class="page-btn active" data-page="1">1</button>
            <button class="page-btn" id="nextPage" disabled>下一页</button>
        </div>
    </div>
</div>

<!-- 添加/编辑模态框 -->
<div class="modal" id="userModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="modalTitle">添加用户</h3>
            <button class="close-btn" id="closeModal">×</button>
        </div>
        <form class="modal-form" id="userForm">
            <input type="hidden" id="userId">

            <div class="form-group">
                <label for="userName" class="form-label">姓名 *</label>
                <input
                        type="text"
                        id="userName"
                        class="form-input"
                        placeholder="请输入姓名"
                        required
                />
            </div>

            <div class="form-group">
                <label for="userEmail" class="form-label">邮箱 *</label>
                <input
                        type="email"
                        id="userEmail"
                        class="form-input"
                        placeholder="请输入邮箱"
                        required
                />
            </div>

            <div class="form-group">
                <label for="userDepartment" class="form-label">部门</label>
                <select id="userDepartment" class="form-select">
                    <option value="">请选择部门</option>
                    <option value="技术部">技术部</option>
                    <option value="产品部">产品部</option>
                    <option value="设计部">设计部</option>
                    <option value="市场部">市场部</option>
                    <option value="人事部">人事部</option>
                </select>
            </div>

            <div class="form-group">
                <label for="userStatus" class="form-label">状态</label>
                <select id="userStatus" class="form-select">
                    <option value="active">活跃</option>
                    <option value="inactive">非活跃</option>
                    <option value="pending">待审核</option>
                </select>
            </div>

            <div class="form-group">
                <label for="userJoinDate" class="form-label">入职日期</label>
                <input
                        type="date"
                        id="userJoinDate"
                        class="form-input"
                />
            </div>

            <div class="modal-buttons">
                <button type="button" class="btn btn-cancel" id="cancelBtn">取消</button>
                <button type="submit" class="btn btn-save">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 数据表格类
    class DataTable {
        constructor() {
            // 初始数据
            this.allData = [
                { id: 1, name: '张三', email: 'zhangsan@example.com', department: '技术部', status: 'active', joinDate: '2023-01-15' },
                { id: 2, name: '李四', email: 'lisi@example.com', department: '产品部', status: 'active', joinDate: '2023-02-20' },
                { id: 3, name: '王五', email: 'wangwu@example.com', department: '设计部', status: 'inactive', joinDate: '2022-11-10' },
                { id: 4, name: '赵六', email: 'zhaoliu@example.com', department: '市场部', status: 'pending', joinDate: '2023-03-05' },
                { id: 5, name: '钱七', email: 'qianqi@example.com', department: '技术部', status: 'active', joinDate: '2023-01-22' },
                { id: 6, name: '孙八', email: 'sunba@example.com', department: '人事部', status: 'active', joinDate: '2023-02-01' },
                { id: 7, name: '周九', email: 'zhoujiu@example.com', department: '产品部', status: 'inactive', joinDate: '2022-12-15' },
                { id: 8, name: '吴十', email: 'wushi@example.com', department: '设计部', status: 'active', joinDate: '2023-03-10' }
            ];

            // 当前显示的数据
            this.currentData = [...this.allData];

            // 分页设置
            this.currentPage = 1;
            this.itemsPerPage = 10;
            this.totalPages = 1;

            // 排序状态
            this.sortColumn = null;
            this.sortDirection = 'asc'; // asc 或 desc

            // 搜索关键词
            this.searchTerm = '';

            // DOM元素
            this.tableBody = document.getElementById('tableBody');
            this.tableContainer = document.getElementById('tableContainer');
            this.searchInput = document.getElementById('searchInput');
            this.addBtn = document.getElementById('addBtn');
            this.userModal = document.getElementById('userModal');
            this.userForm = document.getElementById('userForm');
            this.modalTitle = document.getElementById('modalTitle');
            this.userId = document.getElementById('userId');
            this.userName = document.getElementById('userName');
            this.userEmail = document.getElementById('userEmail');
            this.userDepartment = document.getElementById('userDepartment');
            this.userStatus = document.getElementById('userStatus');
            this.userJoinDate = document.getElementById('userJoinDate');
            this.closeModal = document.getElementById('closeModal');
            this.cancelBtn = document.getElementById('cancelBtn');
            this.prevPage = document.getElementById('prevPage');
            this.nextPage = document.getElementById('nextPage');
            this.pageInfo = document.getElementById('pageInfo');

            // 初始化
            this.init();
        }

        // 初始化方法
        init() {
            // 显示加载状态
            this.showLoading();

            // 模拟数据加载延迟
            setTimeout(() => {
                this.calculateTotalPages();
                this.renderTable();
                this.updatePagination();
                this.bindEvents();
            }, 500);
        }

        // 绑定所有事件监听器
        bindEvents() {
            // 搜索功能
            this.searchInput.addEventListener('input', (e) => {
                this.searchTerm = e.target.value.trim().toLowerCase();
                this.filterData();
            });

            // 添加按钮点击
            this.addBtn.addEventListener('click', () => {
                this.openModal('add');
            });

            // 关闭模态框
            this.closeModal.addEventListener('click', () => {
                this.closeModalBox();
            });

            this.cancelBtn.addEventListener('click', () => {
                this.closeModalBox();
            });

            // 点击模态框外部关闭
            this.userModal.addEventListener('click', (e) => {
                if (e.target === this.userModal) {
                    this.closeModalBox();
                }
            });

            // 表单提交
            this.userForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveUser();
            });

            // 分页按钮
            this.prevPage.addEventListener('click', () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.renderTable();
                    this.updatePagination();
                }
            });

            this.nextPage.addEventListener('click', () => {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.renderTable();
                    this.updatePagination();
                }
            });

            // 表头排序
            document.querySelectorAll('th[data-sort]').forEach(th => {
                th.addEventListener('click', () => {
                    const column = th.dataset.sort;
                    this.handleSort(column);
                });
            });
        }

        // 过滤数据（搜索）
        filterData() {
            if (this.searchTerm === '') {
                this.currentData = [...this.allData];
            } else {
                this.currentData = this.allData.filter(item => {
                    return Object.values(item).some(value =>
                        String(value).toLowerCase().includes(this.searchTerm)
                    );
                });
            }

            this.calculateTotalPages();
            this.currentPage = 1;
            this.renderTable();
            this.updatePagination();
        }

        // 处理排序
        handleSort(column) {
            // 如果是同一列，切换排序方向
            if (this.sortColumn === column) {
                this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                // 新列，默认升序
                this.sortColumn = column;
                this.sortDirection = 'asc';
            }

            // 更新排序图标
            document.querySelectorAll('th .sort-icon').forEach(icon => {
                icon.classList.remove('active');
            });

            const currentIcon = document.querySelector(`th[data-sort="${column}"] .sort-icon`);
            currentIcon.classList.add('active');

            // 执行排序
            this.currentData.sort((a, b) => {
                let valueA = a[column];
                let valueB = b[column];

                // 日期排序特殊处理
                if (column === 'joinDate') {
                    valueA = new Date(valueA);
                    valueB = new Date(valueB);
                }

                if (valueA < valueB) {
                    return this.sortDirection === 'asc' ? -1 : 1;
                }
                if (valueA > valueB) {
                    return this.sortDirection === 'asc' ? 1 : -1;
                }
                return 0;
            });

            this.renderTable();
        }

        // 计算总页数
        calculateTotalPages() {
            this.totalPages = Math.ceil(this.currentData.length / this.itemsPerPage);
            if (this.currentPage > this.totalPages) {
                this.currentPage = Math.max(1, this.totalPages);
            }
        }

        // 渲染表格数据
        renderTable() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            const end = start + this.itemsPerPage;
            const pageData = this.currentData.slice(start, end);

            if (pageData.length === 0) {
                this.tableBody.innerHTML = `
            <tr>
              <td colspan="7" class="empty-state">
                没有找到匹配的数据
              </td>
            </tr>
          `;
                return;
            }

            // 生成表格行
            this.tableBody.innerHTML = pageData.map(item => `
          <tr data-id="${item.id}">
            <td data-label="ID">${item.id}</td>
            <td data-label="姓名">${item.name}</td>
            <td data-label="邮箱">${item.email}</td>
            <td data-label="部门">${item.department}</td>
            <td data-label="状态">
              <span class="status-badge status-${item.status}">
                ${this.getStatusText(item.status)}
              </span>
            </td>
            <td data-label="入职日期">${this.formatDate(item.joinDate)}</td>
            <td data-label="操作" class="action-cell">
              <button class="edit-btn" data-id="${item.id}">编辑</button>
              <button class="delete-btn" data-id="${item.id}">删除</button>
            </td>
          </tr>
        `).join('');

            // 绑定行内操作事件
            this.bindRowEvents();
        }

        // 绑定表格行内事件
        bindRowEvents() {
            // 编辑按钮
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = parseInt(e.target.dataset.id);
                    this.editUser(id);
                });
            });

            // 删除按钮
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = parseInt(e.target.dataset.id);
                    this.deleteUser(id);
                });
            });
        }

        // 显示加载状态
        showLoading() {
            this.tableBody.innerHTML = `
          <tr>
            <td colspan="7" class="loading">
              <span class="loading-spinner"></span>
              <span>加载中...</span>
            </td>
          </tr>
        `;
        }

        // 更新分页信息
        updatePagination() {
            const start = (this.currentPage - 1) * this.itemsPerPage + 1;
            const end = Math.min(this.currentPage * this.itemsPerPage, this.currentData.length);
            const total = this.currentData.length;

            this.pageInfo.textContent = `共 ${total} 条记录，${start}-${end} 条`;

            // 更新分页按钮状态
            this.prevPage.disabled = this.currentPage === 1;
            this.nextPage.disabled = this.currentPage === this.totalPages;

            // 动态生成页码按钮（简化版，只显示当前页前后各1页）
            const paginationControls = document.querySelector('.page-controls');
            const fragment = document.createDocumentFragment();

            // 上一页
            fragment.appendChild(this.prevPage);

            // 页码按钮
            const startPage = Math.max(1, this.currentPage - 1);
            const endPage = Math.min(this.totalPages, this.currentPage + 1);

            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = `page-btn ${i === this.currentPage ? 'active' : ''}`;
                pageBtn.dataset.page = i;
                pageBtn.textContent = i;
                pageBtn.addEventListener('click', () => {
                    this.currentPage = i;
                    this.renderTable();
                    this.updatePagination();
                });
                fragment.appendChild(pageBtn);
            }

            // 下一页
            fragment.appendChild(this.nextPage);

            // 清空并重新添加
            while (paginationControls.firstChild) {
                paginationControls.removeChild(paginationControls.firstChild);
            }
            paginationControls.appendChild(fragment);
        }

        // 打开模态框
        openModal(mode, user = null) {
            // 重置表单
            this.userForm.reset();
            this.userId.value = '';

            if (mode === 'add') {
                this.modalTitle.textContent = '添加用户';
            } else if (mode === 'edit') {
                this.modalTitle.textContent = '编辑用户';
                this.userId.value = user.id;
                this.userName.value = user.name;
                this.userEmail.value = user.email;
                this.userDepartment.value = user.department;
                this.userStatus.value = user.status;
                this.userJoinDate.value = user.joinDate;
            }

            // 显示模态框
            this.userModal.classList.add('show');

            // 自动聚焦到姓名输入框
            this.userName.focus();
        }

        // 关闭模态框
        closeModalBox() {
            this.userModal.classList.remove('show');

            // 清除验证状态（如果有）
            this.userName.classList.remove('invalid');
            this.userEmail.classList.remove('invalid');
        }

        // 保存用户（添加或编辑）
        saveUser() {
            // 简单验证
            if (!this.userName.value.trim()) {
                this.userName.classList.add('invalid');
                this.userName.focus();
                return;
            } else {
                this.userName.classList.remove('invalid');
            }

            if (!this.userEmail.value.trim() || !this.isValidEmail(this.userEmail.value)) {
                this.userEmail.classList.add('invalid');
                this.userEmail.focus();
                return;
            } else {
                this.userEmail.classList.remove('invalid');
            }

            const user = {
                id: this.userId.value ? parseInt(this.userId.value) : this.getNextId(),
                name: this.userName.value.trim(),
                email: this.userEmail.value.trim(),
                department: this.userDepartment.value,
                status: this.userStatus.value,
                joinDate: this.userJoinDate.value || this.getCurrentDate()
            };

            if (this.userId.value) {
                // 编辑模式
                const index = this.allData.findIndex(u => u.id === user.id);
                if (index !== -1) {
                    this.allData[index] = user;
                }
            } else {
                // 添加模式
                this.allData.unshift(user); // 添加到开头
            }

            // 重新过滤和渲染
            this.filterData();

            // 关闭模态框
            this.closeModalBox();

            // 显示成功提示（实际项目中可以添加toast通知）
            console.log('用户保存成功:', user);
        }

        // 编辑用户
        editUser(id) {
            const user = this.allData.find(u => u.id === id);
            if (user) {
                this.openModal('edit', user);
            }
        }

        // 删除用户
        deleteUser(id) {
            if (confirm('确定要删除这个用户吗？')) {
                this.allData = this.allData.filter(u => u.id !== id);
                this.filterData();
            }
        }

        // 获取下一个ID
        getNextId() {
            return this.allData.length > 0
                ? Math.max(...this.allData.map(u => u.id)) + 1
                : 1;
        }

        // 获取当前日期（格式：YYYY-MM-DD）
        getCurrentDate() {
            const now = new Date();
            return now.toISOString().split('T')[0];
        }

        // 验证邮箱格式
        isValidEmail(email) {
            const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return regex.test(email);
        }

        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                'active': '活跃',
                'inactive': '非活跃',
                'pending': '待审核'
            };
            return statusMap[status] || status;
        }

        // 格式化日期显示
        formatDate(dateString) {
            if (!dateString) return '';
            const options = { year: 'numeric', month: 'short', day: 'numeric' };
            return new Date(dateString).toLocaleDateString('zh-CN', options);
        }
    }

    // 页面加载完成后初始化数据表格
    document.addEventListener('DOMContentLoaded', function() {
        // 创建数据表格实例
        const dataTable = new DataTable();

        // 页面加载动画
        setTimeout(() => {
            document.getElementById('tableContainer').style.transform = 'translateY(-20px)';
            document.getElementById('tableContainer').style.opacity = '0.8';

            setTimeout(() => {
                document.getElementById('tableContainer').style.transform = 'translateY(0)';
                document.getElementById('tableContainer').style.opacity = '1';
            }, 100);
        }, 100);
    });
</script>
</body>
</html>